<template>
  <div class="app-container">
    

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleImport"
          v-hasPermi="['order:original:add']"
        >批量导入原片</el-button>
      </el-col>
      <el-col :span="1.5" class="right-align-col">
        <el-button
          type="success"
          plain
          icon="CircleCheck"
          @click="handleNext"
          v-hasPermi="['order:original:edit']"
        >下一步</el-button>
      </el-col>
 
    </el-row>

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="批次" prop="batch">
        <el-input
          v-model="queryParams.batch"
          placeholder="请输入批次"
          @keyup.enter="handleQuery"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-input
          v-model="queryParams.type"
          placeholder="请输入类型"
          @keyup.enter="handleQuery"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="宽度" prop="beginWidth">
        <el-input
          v-model="queryParams.beginWidth"
          placeholder="请输入宽度下限"
          @keyup.enter="handleQuery"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="" prop="endWidth">
        <el-input
          v-model="queryParams.endWidth"
          placeholder="请输入宽度上限"
          @keyup.enter="handleQuery"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="高度" prop="beginLength">
        <el-input
          v-model="queryParams.beginLength"
          placeholder="请输入高度下限"
          @keyup.enter="handleQuery"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="" prop="endLength">
        <el-input
          v-model="queryParams.endLength"
          placeholder="请输入高度上限"
          @keyup.enter="handleQuery"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="价格" prop="beginPrice">
        <el-input
          v-model="queryParams.beginPrice"
          placeholder="请输入价格下限"
          @keyup.enter="handleQuery"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="" prop="endPrice">
        <el-input
          v-model="queryParams.endPrice"
          placeholder="请输入价格上限"
          @keyup.enter="handleQuery"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="可用片数" prop="beginAvailableNumber">
        <el-input
          v-model="queryParams.beginAvailableNumber"
          placeholder="请输入可用片数下限"
          @keyup.enter="handleQuery"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="" prop="endAvailableNumber">
        <el-input
          v-model="queryParams.endAvailableNumber"
          placeholder="请输入可用片数上限"
          @keyup.enter="handleQuery"
          style="width: 120px"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="selectAll" @change="selectAllChange" label="全选" />
    </el-form-item>
    
    </el-form>

    <el-table v-loading="loading" :data="originalList" @selection-change="handleSelectionChange" 
    @sort-change="handleSortChange">
      <el-table-column label="批次" align="center" sortable="custom" prop="batch" />
      <el-table-column label="类型" align="center" sortable="custom" prop="type" />
      <el-table-column label="厚度" align="center" sortable="custom" prop="thickness" />
      <el-table-column label="宽度" align="center" sortable="custom" prop="width" />
      <el-table-column label="高度" align="center" sortable="custom" prop="length" />
      <el-table-column label="可用片数" align="center" sortable="custom" prop="availableNumber" >
        <template #default="scope">
          <el-input-number
            v-model="scope.row.availableNumber"
            @change="handleUpdate(scope.row)"
            controls-position="right"
            :min="0"
            :step="1"
            placeholder="请输入可用片数"
            style="width: 100px"
          />
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" sortable="custom" prop="price">
        <template #default="scope">
          <el-input-number
            v-model="scope.row.price"
            @change="handleUpdate(scope.row)"
            placeholder="请输入价格"
            controls-position="right"
            :min="0"  
            :step="0.01"
            :precision="2"
            style="width: 100px"
            
          />
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" sortable="custom" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="累计用量" align="center" sortable="custom" prop="totalUsed" />
      <el-table-column label="本月用量" align="center" sortable="custom" prop="monthUsed" />
      <el-table-column label="操作" align="center"  class-name="small-padding fixed-width">
        <template #default="scope">
          <el-select  
            v-model="scope.row.status" 
            placeholder="请选择状态"  
            size="small" 
            @change="selectChanged(scope.row)" 
            style="width:80%;"
            :default-first-option="true">
            <el-option label="优先" value="2" />
            <el-option label="使用" value="1" />
            <el-option label="不使用" value="0" />
          </el-select>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改原片对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="originalRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="批次" prop="batch">
          <el-input v-model="form.batch" placeholder="请输入批次" />
        </el-form-item>
        <el-form-item label="厚度" prop="thickness">
          <el-input v-model="form.thickness" placeholder="请输入厚度" />
        </el-form-item>
        <el-form-item label="宽度" prop="width">
          <el-input v-model="form.width" placeholder="请输入宽度" />
        </el-form-item>
        <el-form-item label="高度" prop="length">
          <el-input v-model="form.length" placeholder="请输入高度" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="累计用量" prop="totalUsed">
          <el-input v-model="form.totalUsed" placeholder="请输入累计用量" />
        </el-form-item>
        <el-form-item label="本月用量" prop="monthUsed">
          <el-input v-model="form.monthUsed" placeholder="请输入本月用量" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

          <!-- 批量导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
         <el-upload
            ref="uploadRef"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag
         >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
               <div class="el-upload__tip text-center">
                  <span>仅允许导入xls、xlsx格式文件。</span>
               </div>
            </template>
         </el-upload>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitFileForm">确 定</el-button>
               <el-button @click="upload.open = false">取 消</el-button>
            </div>
         </template>
      </el-dialog>

  </div>
</template>

<script setup name="Original">
import { getToken } from "@/utils/auth";
import { listOriginal, getOriginal, delOriginal, addOriginal, updateOriginal } from "@/api/order/original";
import useOrderStore from '@/store/modules/order'

const { proxy } = getCurrentInstance();
const orderStore = useOrderStore();

const originalList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const selectAll = ref(false);
const selectOriginalIds = ref([])
const priorityOriginalIds = ref([])
const router = useRouter();

/*** 货架导入参数 */
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题（批量导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/order/original/importData"
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    createrId: null,
    batch: null,
    type: null,
    thickness: null,
    width: null,
    length: null,
    availableNumber: null,
    price: null,
    updateTime: null,
    totalUsed: null,
    monthUsed: null,
    beginThickness: null,
    endThickness: null,
    beginWidth: null,
    endWidth: null,
    beginLength: null,
    endLength: null,
    beginPrice: null,
    endPrice: null,
    beginAvailableNumber: null,
    endAvailableNumber: null,
  },
  rules: {
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
    createrId: [
      { required: true, message: "创建者id不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询原片列表 */
function getList() {
  //loading.value = true;
  queryParams.value.thickness = orderStore.ordersThicknessList[0] || null;
  listOriginal(queryParams.value).then(response => {
    originalList.value = response.rows;
    originalList.value.forEach(item => {
      if (selectOriginalIds.value.includes(item.id)) {
        item.status = '1';
      } else if (priorityOriginalIds.value.includes(item.id)) {
        item.status = '2';
      } else {
        item.status = '0';
      }
    });
    total.value = response.total;
    loading.value = false;
  });
  loading.value = false;
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    createTime: null,
    createrId: null,
    batch: null,
    type: null,
    thickness: null,
    width: null,
    length: null,
    price: null,
    updateTime: null,
    totalUsed: null,
    monthUsed: null
  };
  proxy.resetForm("originalRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加原片";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  updateOriginal(row).then(response => {
    getList();
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["originalRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateOriginal(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOriginal(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除原片编号为"' + _ids + '"的数据项？').then(function() {
    return delOriginal(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}


/** 批量导入操作 */
function handleImport() {
  upload.title = "用户导入";
  upload.open = true;
}

/** 提交上传文件 */
function submitFileForm() {
  console.log(proxy.$refs["uploadRef"])
  proxy.$refs["uploadRef"].submit();
};

function selectAllChange(selection) {
  if(selection) {
    for(let i = 0; i < originalList.value.length; i++) {
      if (originalList.value[i].status === undefined || originalList.value[i].status === "0") {
        originalList.value[i].status = "1"
      } 
    }
  } else {
    for(let i = 0; i < originalList.value.length; i++) {
      originalList.value[i].status = "0"
    }
  }
}

function selectChanged(row) {
  const selection = row.status

  if(selection == "0"){
    selectAll.value = false
    selectOriginalIds.value = selectOriginalIds.value.filter(id => id != row.id);
    priorityOriginalIds.value = priorityOriginalIds.value.filter(id => id != row.id);
  }else {
    if(selection == "2") {
      priorityOriginalIds.value.push(row.id);
      selectOriginalIds.value = selectOriginalIds.value.filter(id => id != row.id);
    } else {
      selectOriginalIds.value.push(row.id);
      priorityOriginalIds.value = priorityOriginalIds.value.filter(id => id != row.id);
    }
    let check = true
    for(let i = 0; i < originalList.value.length; i++) {
      if( typeof originalList.value[i].status === 'undefined') {
        check = false
        break
      } else if(originalList.value[i].status === "0"){
        check = false
        break
      }
    }
    selectAll.value = check
  }
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};

function handleSortChange(column) {
  queryParams.value.orderByColumn = column.prop;
  if(column.order == 'ascending') {
    queryParams.value.isAsc = 'ASC';
  } else if(column.order == 'descending') {
    queryParams.value.isAsc = 'DESC';
  } else {
    queryParams.value.isAsc = null;
    queryParams.value.orderByColumn = null;
  }
  getList();
}

/** 下一步操作 */
function handleNext() {
  
  if (selectOriginalIds.value.length == 0 && priorityOriginalIds.value.length == 0) {
    proxy.$modal.msgError("请选择至少一个原片");
    return;
  }
  orderStore.setOriginalIds(selectOriginalIds.value);
  orderStore.setPriorityOriginalIds(priorityOriginalIds.value);
  router.push("/order/paramconfig");
}

onMounted(() => {
  selectOriginalIds.value = orderStore.originalIds;
  priorityOriginalIds.value = orderStore.priorityOriginalIds;
  queryParams.value.thickness = orderStore.ordersThicknessList[0];
  //getList();
})

onActivated(() => {
  getList();
})


</script>
<style scoped>
.right-align-col {
  margin-left: auto;
}


</style>